package com.mogician.qrrelay.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.security.Permission;
import java.util.ArrayList;

public class PermissionUtil
{
    public static boolean hasPermission(Context context, String permission)
    {
        return ContextCompat.checkSelfPermission(context, permission)
                == PackageManager.PERMISSION_GRANTED;
    }

    public static boolean allGranted(Context context, int[] grantResults)
    {
        if(grantResults.length == 0)
            return false;
        for(int result : grantResults)
        {
            if(result == PackageManager.PERMISSION_DENIED)
                return false;
        }
        return true;
    }

    public static boolean requestPermission(Activity activity, String[] permissions, int requestCode)
    {
        ArrayList<String> toPermitList = new ArrayList<>();
        for(String permission : permissions)
        {
            if(!hasPermission(activity, permission))
                toPermitList.add(permission);
        }
        int size = toPermitList.size();
        if(size > 0)
        {
            ActivityCompat.requestPermissions(activity,
                    (String[]) toPermitList.toArray(new String[size]),
                    requestCode);
            return false;
        }
        else
            return true;//不需要申请，直接执行
    }
}
